from flask import Flask, render_template, request, jsonify, send_file
import os
import time
from datetime import datetime
from code_generator import generate_documentation

app = Flask(__name__)

# 存储进度信息的全局变量
progress_info = {
    'current_step': 0,
    'total_steps': 3,
    'debug_info': []
}

def update_progress(step_name, debug_info=None):
    """更新进度信息"""
    progress_info['current_step'] += 1
    progress_info['step_name'] = step_name
    if debug_info:
        progress_info['debug_info'].append(f"步骤 {progress_info['current_step']}: {debug_info}")
    print(f"进度更新: {progress_info['current_step']}/{progress_info['total_steps']} - {step_name}")
    if debug_info:
        print(f"调试信息: {debug_info}")

@app.route('/')
def index():
    return render_template('index.html')

@app.route('/progress')
def get_progress():
    """获取当前进度信息"""
    return jsonify({
        'current_step': progress_info['current_step'],
        'total_steps': progress_info['total_steps'],
        'step_name': progress_info.get('step_name', ''),
        'progress_percent': int((progress_info['current_step'] / progress_info['total_steps']) * 100),
        'debug_info': progress_info['debug_info']
    })

@app.route('/generate', methods=['POST'])
def generate():
    project_description = request.form.get('project_description', '')
    
    if not project_description:
        return jsonify({'error': '请输入项目描述'}), 400
    
    print(f"收到生成请求，项目描述长度: {len(project_description)}")
    
    # 重置进度信息
    progress_info['current_step'] = 0
    progress_info['debug_info'] = []
    
    try:
        start_time = time.time()
        
        # 生成文档（传入进度回调函数）
        print("开始生成文档...")
        global_role, project_plan, detail_task = generate_documentation(
            project_description, 
            progress_callback=update_progress
        )
        
        print(f"文档生成完成，耗时: {time.time() - start_time:.2f}秒")
        
        # 保存文件
        timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
        
        global_role_file = f"global_role_{timestamp}.md"
        project_plan_file = f"project_plan_{timestamp}.md"
        detail_task_file = f"detail_task_{timestamp}.md"
        
        with open(global_role_file, 'w', encoding='utf-8') as f:
            f.write(global_role)
        with open(project_plan_file, 'w', encoding='utf-8') as f:
            f.write(project_plan)
        with open(detail_task_file, 'w', encoding='utf-8') as f:
            f.write(detail_task)
        
        print(f"文件保存完成: {global_role_file}, {project_plan_file}, {detail_task_file}")
        
        return jsonify({
            'global_role': global_role_file,
            'project_plan': project_plan_file,
            'detail_task': detail_task_file
        })
    
    except Exception as e:
        print(f"生成文档时出错: {str(e)}")
        import traceback
        traceback.print_exc()
        return jsonify({'error': f'生成文档时出错: {str(e)}'}), 500

@app.route('/download/<filename>')
def download_file(filename):
    try:
        return send_file(filename, as_attachment=True)
    except FileNotFoundError:
        return jsonify({'error': '文件不存在'}), 404

if __name__ == '__main__':
    app.run(debug=True, host='0.0.0.0', port=5000)
